package com.zhangc.blog.admin.web.controller;

import java.util.Collections;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.zhangc.blog.admin.entity.RoleEntity;
import com.zhangc.blog.admin.entity.UserEntity;
import com.zhangc.blog.admin.service.UserService;
import com.zhangc.blog.admin.web.dto.AddUserRequest;
import com.zhangc.blog.admin.web.dto.JwtAuthenticationResponse;
import com.zhangc.blog.admin.web.dto.LoginRequest;
import com.zhangc.blog.admin.web.security.JwtTokenProvider;
import com.zhangc.blog.base.ResultBO;

/**
 * 功能描述:<br>
 *
 * @author wx:fdzhangc
 * @see [相关类/方法]（可选）
 * @since [产品/模块版本] （可选）
 */
@RestController
@RequestMapping("/api/auth")
public class AuthController {
    @Autowired
    JwtTokenProvider tokenProvider;
    @Autowired
    AuthenticationManager authenticationManager;
    @Autowired
    UserService userService;
    @Autowired
    PasswordEncoder passwordEncoder;

    @PostMapping("/login")
    public ResultBO<?> authenticateUser(@RequestBody LoginRequest loginRequest) {

        Authentication authentication = authenticationManager.authenticate(
                new UsernamePasswordAuthenticationToken(
                        loginRequest.getUsernameOrEmail(),
                        loginRequest.getPassword()
                )
        );

        SecurityContextHolder.getContext().setAuthentication(authentication);

        String jwt = tokenProvider.generateToken(authentication);
        return ResultBO.of(new JwtAuthenticationResponse(jwt));
    }

    @GetMapping("/getpwd")
    public ResultBO<?> createPws(String pwd) {
        return ResultBO.of(passwordEncoder.encode(pwd));
    }

    @PostMapping("/register")
    public ResultBO<?> registerUser(@RequestBody AddUserRequest request) {
        UserEntity userEntity = new UserEntity();
        userEntity.setName(request.getName());
        userEntity.setEmail(request.getEmail());
        userEntity.setUserName(request.getUsername());
        RoleEntity roleEntity = new RoleEntity();
        roleEntity.setRoleId("r1");
        roleEntity.setRoleName("rname");
        userEntity.setRoles(Collections.singleton(roleEntity));
        userEntity.setPwd(passwordEncoder.encode(request.getPassword()));
        userService.addUser(userEntity);
        return ResultBO.success();
    }
}
